package jmu.controller;

import jakarta.servlet.http.HttpSession;
import jmu.service.RevertService;
import jmu.vo.Revert;
import jmu.vo.Students;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;

@Controller
@RequestMapping("/reverts")
public class RevertController {

    @Autowired
    private RevertService revertService;

    @PostMapping("/add")
    public String addRevert(@ModelAttribute Revert revert,
                            HttpSession session,
                            RedirectAttributes redirectAttributes) {
        // 1. 校验登录状态
        Students currentUser = (Students) session.getAttribute("currentUser");
        if (currentUser == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/students/login";
        }

        // 2. 设置回复信息
        revert.setWriter(currentUser.getStudentName());
        revert.setWriteDate(new Date());

        // 3. 保存回复
        if (revertService.insertRevert(revert)) {
            redirectAttributes.addFlashAttribute("revertSuccess", true);
        } else {
            redirectAttributes.addFlashAttribute("error", "回复提交失败");
        }

        return "redirect:/messages/list";
    }

    @GetMapping("/delete/{id}")
    public String deleteRevert(@PathVariable int id,
                               HttpSession session,
                               RedirectAttributes redirectAttributes) {
        // 1. 校验登录状态
        Students currentUser = (Students) session.getAttribute("currentUser");
        if (currentUser == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/students/login";
        }

        // 2. 获取回复信息
        Revert revert = revertService.findById(id);
        if (revert == null) {
            redirectAttributes.addFlashAttribute("error", "回复不存在");
            return "redirect:/messages/list";
        }

        // 3. 权限校验
        if (!revert.getWriter().equals(currentUser.getStudentName())) {
            redirectAttributes.addFlashAttribute("error", "无权删除他人回复");
            return "redirect:/messages/list";
        }

        // 4. 执行删除
        if (revertService.deleteRevert(id)) {
            redirectAttributes.addFlashAttribute("deleteSuccess", true);
        } else {
            redirectAttributes.addFlashAttribute("error", "删除失败");
        }

        return "redirect:/messages/list";
    }
}